
#include "pcardviewer.h"

#include "cardviewer.h"
#include "cardviewwidget.h"

#include "sqlite3stmt.h"

/* 
 *  Constructs a PCardViewer which is a child of 'parent', with the 
 *  name 'name' and widget flags set to 'f' 
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
PCardViewer::PCardViewer( int c, sqlite3* s, QWidget* parent, const char* name, bool modal, Qt::WFlags fl )
    : QDialog(parent, name, modal, fl),
      sql(s),
      card_t_n(c)    
{
  setupUi(this);

  top_view_widget->load(c,sql);

  refresh_holdings();
}

/*  
 *  Destroys the object and frees any allocated resources
 */
PCardViewer::~PCardViewer()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void PCardViewer::languageChange()
{
    retranslateUi(this);
}

void PCardViewer::refresh_holdings() {
  QString r;
  r = "SELECT cards.ROWID, releases.rname, card_ver.rarity, decks.dname, cards.comments";
  r += " FROM card_ver, releases, cards, decks";
  r += " WHERE releases.rnum==card_ver.ver ";
  r +=    "AND card_ver.rowid==cards.printing ";
  r +=    "AND decks.dnum==cards.deck ";
  r +=    "AND card_ver.card=="+QString::number(card_t_n)+";";

  lvHoldings->clear();

  for(sqlite3Stmt s(sql,r) ; !s.done() ; s.step()) {
    new Q3ListViewItem( lvHoldings,
                       s.column_text(0),
                       s.column_text(1),
                       s.column_text(2),
                       s.column_text(3),
                       s.column_text(4) );
  }
}

/*
 * public slot
 */
void PCardViewer::save_data()
{
  top_view_widget->save();
  accept();
}

/*
 * public slot
 */
void PCardViewer::add_card()
{
  QString q = "INSERT INTO cards (printing) SELECT card_ver.ROWID FROM card_ver, releases ";
  q += "WHERE card_ver.card=="+QString::number(card_t_n)+" ";
  q +=   "AND releases.rnum==card_ver.ver ";
  q +=   "AND releases.rname=='"+top_view_widget->cbPrinting->currentText()+"';";

  // Should only get one...
  sqlite3Stmt stmt(sql,q);
  refresh_holdings();
}

/*
 * public slot
 */
void PCardViewer::remove_card()
{
  Q3ListViewItem* i = lvHoldings->selectedItem();
  if(i==0)
    return;

  QString q = "DELETE FROM cards WHERE cards.ROWID=="+i->text(0)+";";

  // Should only get one...
  sqlite3Stmt stmt(sql,q);
  refresh_holdings();
}

/*
 * public slot
 */
void PCardViewer::edit_card()
{
  Q3ListViewItem *i = lvHoldings->currentItem();

  if(i==0)
    return;

  CardViewer v(i->text(0).toInt(),sql,this,0,TRUE);
  v.exec();
  refresh_holdings();
  top_view_widget->refresh();

}
